
import React, { useState, useEffect } from 'react'
import { Row, Col, Space, Input, DatePicker, Select, Form, Cascader } from 'antd'
import MyButton from '../../../components/customerseas/MyButton'
import CheckBtn from '../../../components/customerseas/CheckBtn'
import store from '../../../redux/store';
import { AsyncGetOptionAction } from '../../../redux/action/customerAction/option';
import { AsyncTableDataAction } from '../../../redux/action/customerAction/tableData';
import myAxios from '../../../utils/myAxios';
import chinaDivision from './../../../utils/chinaDivision';
const { RangePicker } = DatePicker;
const { Option } = Select;
//复选按钮数组
const checkArr = [
  { id: '1', title: '有跟单', check: false },
  { id: '2', title: '有订单', check: false },
  { id: '3', title: '有合同', check: false },
  { id: '4', title: '有售后', check: false },
  { id: '5', title: '有附件', check: false }]
export default function Search() {

  const options = chinaDivision

  //初始化，获取所有下拉选项
  useEffect(() => {
    // 获取所有下拉的异步action
    store.dispatch(AsyncGetOptionAction())

    let fn = store.subscribe(() => {
      setjobList(store.getState().customerReducer.optionReducer.customerPosition)
      setcustomerType(store.getState().customerReducer.optionReducer.customerType)
      setcustomerSource(store.getState().customerReducer.optionReducer.customerSource)
      setcustomerIndustry(store.getState().customerReducer.optionReducer.customerIndustry)
      setcustomerLevel(store.getState().customerReducer.optionReducer.customerLevel)
      setbigClass(bC(store.getState().customerReducer.optionReducer.comSort))
      setemployee(store.getState().customerReducer.optionReducer.employee)
      setdepartment(store.getState().customerReducer.optionReducer.department)
    })
    return () => {
      fn()
    }
  }, [])


  //写一个方法，来处理商品分类
  function bC(arr) {
    let tempArr = []
    arr.forEach(element => {
      tempArr.push(element.bigClass)
    });
    return tempArr
  }

  const [jobList, setjobList] = useState([]);
  const [customerType, setcustomerType] = useState([]);
  const [customerSource, setcustomerSource] = useState([]);
  const [customerIndustry, setcustomerIndustry] = useState([]);
  const [customerLevel, setcustomerLevel] = useState([]);
  const [bigClass, setbigClass] = useState([]);
  const [smallClass, setsmallClass] = useState([]);
  const [employee, setemployee] = useState([]);
  const [department, setdepartment] = useState([]);


  //选择了大类以后，再去请求对应小类的数据
  const handleProvinceChange = value => {
    //修改了大类之后，需要把之前选择的小类选项置空
    form.setFieldsValue({
      smallClass: ''
    })
    //选择了大类以后，再去请求对应小类的数据
    const handleProvinceChange = value => {
      //修改了大类之后，需要把之前选择的小类选项置空
      form.setFieldsValue({
        smallClass: ''
      })
      myAxios({
        method: 'get',
        url: '/customer/customerComSort/findSmallClass',
        headers: {
          'isLoading': false
        },
        params: { bigClass: value }
      })
        .then(res => {
          console.log(res.data.data);
          let tempArr = []
          res.data.data.forEach(item => {
            tempArr.push(item.smallClass)
          })
          setsmallClass(tempArr);
          // setCities(smallClass[value]);
        })

    };
    myAxios({
      method: 'get',
      url: '/customer/customerComSort/findSmallClass',
      headers: {
        'isLoading': false
      },
      params: { bigClass: value }
    })
      .then(res => {
        console.log(res.data.data);
        let tempArr = []
        res.data.data.forEach(item => {
          tempArr.push(item.smallClass)
        })
        setsmallClass(tempArr);
      })

  };


  //清空清除按钮选中的状态
  const [stateBtn, setstateBtn] = useState(checkArr);
  const [form] = Form.useForm();
  //联动select下拉框
  const [secondCity, setSecondCity] = React.useState('请选择');

  const onSecondCityChange = value => {
    setSecondCity(value);
  };
  const onFinish = (values) => {
    console.log(values);
    const { insertTime, updateTime, region } = values
    const checkBtnArr = stateBtn.filter((item) => item.check)
    // const formArr = values.splite(',').filter((item) => item)
    console.log('选中按钮', checkBtnArr);

    let insertTimeStart, insertTimeEnd, updateTimeStart, updateTimeEnd, obj
    if (insertTime) {
      insertTimeStart = insertTime[0].format('YYYY-MM-DD')
      insertTimeEnd = insertTime[1].format('YYYY-MM-DD')
    }
    if (updateTime) {
      updateTimeStart = updateTime[0].format('YYYY-MM-DD')
      updateTimeEnd = updateTime[1].format('YYYY-MM-DD')
    }
    if (region) {
      obj = { ...values, insertTimeStart, insertTimeEnd, updateTimeStart, updateTimeEnd, province: region[0], city: region[1], area: region[2] }
      delete obj.region
      delete obj.insertTime
      delete obj.updateTime
    } else {
      obj = { ...values, insertTimeStart, insertTimeEnd, updateTimeStart, updateTimeEnd }
    }
    console.log(obj);
    //整合所有需要的数据
    let deleteCustomerVo = {
      ...obj,
      afterSaleType: 1,
      contractType: 1,
      documentaryType: 1,
      enclosureType: 1,
      orderType: 1,
    }
    checkBtnArr.forEach(item => {
      if (item.title == '售后') {
        deleteCustomerVo.afterSaleType = 2
      } else if (item.title == '跟单') {
        deleteCustomerVo.documentaryType = 2
      } else if (item.title == '订单') {
        deleteCustomerVo.orderType = 2
      } else if (item.title == '合同') {
        deleteCustomerVo.contractType = 2
      } else if (item.title == '附件') {
        deleteCustomerVo.enclosureType = 2
      }
    })
    //发起高级查询请求
    store.dispatch(AsyncTableDataAction(1, 7, 0, 0, 1, '', 3, '', deleteCustomerVo))


  };
  //子组件按钮传递id
  const getChecked = (id) => {
    stateBtn.forEach((item) => {
      if (item.id == id) {
        item.check = !item.check
      }
    })
    setstateBtn(stateBtn.concat([]))
  }

  //清空搜索框
  function resetFrom() {
    form.resetFields();
    stateBtn.forEach((item) => {
      item.check = false
    })
  }

  //省市区选择部分
  function onChange(value) {
    console.log(value);
  }
  return (
    <>
      <div style={{ width: '100%', border: '1px solid #e1e2e4', borderRadius: '10px', padding: '15px', margin: '15px 0', backgroundColor: '#eff0ef' }}>
        <Form
          wrapperCol={{ span: 16 }}
          labelCol={{ span: 4 }}
          form={form}
          name="advanced_search"
          className="ant-advanced-search-form"
          onFinish={onFinish}
        >
          <Row gutter={24} justify='space-between'>
            {/* 第一列表单 */}
            <Col span={8} >
              <Form.Item
                name='id'
                label='编号'
              >
                <Input />
              </Form.Item>
              <Form.Item
                name='customerPosition'
                label='职位'
              >
                <Select placeholder="请选择">
                  <Option value="0" disabled >请选择</Option>
                  {jobList.map((item) => {
                    return <Option value={item.id} key={item.id}>{item.title}</Option>
                  })}
                </Select>

              </Form.Item>
              <Form.Item
                name='website'
                label='网址'
              >
                <Input />
              </Form.Item>
              <Form.Item
                name='updateTime'
                label='最后更新'
              >
                <RangePicker />
              </Form.Item>
              <Form.Item
                name='address'
                label='详细地址'
              >
                <Input />
              </Form.Item>
              <Form.Item
                name='remarks'
                label='备注'
              >
                <Input />
              </Form.Item>
              <Form.Item
                name='customerSource'
                label='客户来源'
              >
                <Select placeholder="请选择" >
                  <Option value="0" disabled >请选择</Option>
                  {customerSource.map((item) => {
                    return <Option value={item.id} key={item.id}>{item.title}</Option>
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                name='employeeInputName'
                label='录入者'
              >
                <Select placeholder="请选择" >
                  <Option value="0" disabled >请选择</Option>
                  {employee.map((item, index) => {
                    return <Option value={item.name} key={item.id}>{item.name}</Option>
                  })}
                </Select>
              </Form.Item>
            </Col>
            {/* 第二列表单 */}
            <Col span={8} >
              <Form.Item name='customerUsername' label='客户名称'>
                <Input />
              </Form.Item>
              <Form.Item name='phoneNumber' label='手机号'>
                <Input />
              </Form.Item>
              <Form.Item
                name='customerIndustry'
                label='所属行业'
              >
                <Select placeholder="请选择" >
                  <Option value="0" disabled >请选择</Option>
                  {customerIndustry.map((item) => {
                    return <Option key={item.id} value={item.id} >{item.title}</Option>
                  })}
                </Select>
              </Form.Item>
              <Form.Item label="所在地区" name="region" >
                <Cascader options={options} onChange={onChange} placeholder="请选择" />
              </Form.Item>
              <Form.Item
                name='postal'
                label='邮编'
              >
                <Input />
              </Form.Item>
              <Form.Item
                name='customerType'
                label='客户类型'
              >
                <Select placeholder="请选择" >
                  <Option value="0" disabled >请选择</Option>
                  {customerType.map((item) => {
                    return <Option value={item.id} key={item.id}>{item.title}</Option>
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                label='商品类别'
              >
                <Space size='small'>
                  <Form.Item name='bigClass'>
                    <Select placeholder="请选择" style={{ width: 130 }} onChange={handleProvinceChange}>
                      {bigClass.map((province, index) => (
                        <Option key={province}>{province}</Option>
                      ))}
                    </Select>

                  </Form.Item>
                  <Form.Item name='smallClass'>
                    <Select placeholder="请选择" style={{ width: 130 }} value={secondCity} onChange={onSecondCityChange}>
                      {smallClass.map((city, index) => (
                        <Option key={index}>{city}</Option>
                      ))}
                    </Select>

                  </Form.Item>
                </Space>
              </Form.Item>
              <Form.Item
                name='employeeName'
                label='业务员'
              >
                <Select placeholder="请选择" >
                  <Option value="0" disabled >请选择</Option>
                  {employee.map((item, index) => {
                    return <Option value={item.name} key={item.id}>{item.name}</Option>
                  })}
                </Select>
              </Form.Item>

            </Col>
            {/* 第三列表单 */}
            <Col span={8} >
              <Form.Item
                name='customerName'
                label='联系人'
              >
                <Input />
              </Form.Item>
              <Form.Item label="电子邮箱" name="email"
              >
                <Input />
              </Form.Item>
              <Form.Item
                name='insertTime'
                label='录入时间'
              >
                <RangePicker />
              </Form.Item>
              <Form.Item
                name='qqNumber'
                label='QQ'
              >
                <Input />
              </Form.Item>
              <Form.Item
                name='customerLevel'
                label='客户级别'
              >
                <Select placeholder="请选择" >
                  <Option value="0" disabled >请选择</Option>
                  {customerLevel.map((item) => {
                    return <Option value={item.id} key={item.id}>{item.title}</Option>
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                name='department'
                label='部门'
              >
                <Select placeholder="请选择" >
                  <Option value="0" disabled >请选择</Option>
                  {department.map((item) => {
                    return <Option value={item.departmentName} key={item.departmentName}>{item.departmentName}</Option>
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Space>
                <div style={{ width: 58, textAlign: 'right' }}>其他 :</div>
                {/* 复选按钮组件，传递方法和要渲染的按钮数组 */}
                <CheckBtn click={getChecked} stateBtn={stateBtn} />
              </Space>
            </Col>
          </Row>
          {/* 提交按钮 */}
          <Row align='middle'>
            <Col span={4} offset={10} style={{ fontSize: '38px', padding: '10px 0' }}>
              <Space>
                <MyButton size="middle" color='#49b377' htmlType="submit" title='立即搜索' />
                <MyButton size="middle" color='#505050' onClick={resetFrom} title='清空条件' />
                <MyButton size="middle" color='#b1b3b2' title='导出数据' />
              </Space>
            </Col>
          </Row>
        </Form>
      </div>
    </>
  )
}
